
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include "Socket-Server.h"

//#include <arpa/inet.h>

int32_t CreaConexionServer_INET(int32_t puerto){

		int32_t Sock;
		int32_t yes =1;
		struct sockaddr_in direccion;
		memset(&direccion, 0, sizeof(struct sockaddr_in));

		if((Sock = socket(AF_INET, SOCK_STREAM, 0))== -1 )
		{
			printf ("error SOCKET");
		}
		direccion.sin_family= AF_INET;
		direccion.sin_addr.s_addr = INADDR_ANY;
		direccion.sin_port = htons(puerto);
		if(setsockopt(Sock, SOL_SOCKET , SO_REUSEADDR , &yes ,sizeof(yes))==-1){
			perror("setsockopt");
			close(Sock);
			exit(1);
		}
		if(bind(Sock,(struct sockaddr*) &direccion,  sizeof(direccion))==-1)
		{
			printf ("error BIND");

		}
		listen(Sock,1);

		return Sock;

}

void list_sockets_add(list_sockets * aList, int32_t aDescriptor)
{
	nodo_socket * aux;
	aux = (nodo_socket *)calloc(1, sizeof(nodo_socket));
	aux->descriptor = aDescriptor;
	aux->nxt = aList->list;
	aList->list = aux;
}

int32_t list_sockets_exists(list_sockets * aList, int32_t descriptor) //-1 si no existe 0 si existe
{
	nodo_socket * aux = aList->list;
	while(aux != NULL && aux->descriptor != descriptor)
		aux = aux->nxt;
	if(aux != NULL)
		return 0;
	else
		return -1;
}

int32_t list_sockets_delete(list_sockets * aList, int32_t descriptor)
{
	nodo_socket * aux = aList->list;
	nodo_socket * ant = aList->list;
	while(aux != NULL && aux->descriptor != descriptor) {
		ant = aux;
		aux = aux->nxt;
	}
	if(aux != NULL) {
		if (aux == ant) {
			aList->list = aux->nxt;
			free(aux);
		}
		else {
			ant->nxt = aux->nxt;
			free(aux);
		}
		return 0;
	}
	else
		return -1;

}
